$(function () {
    //用户趋势看板时间切换监听器
    document.getElementById("user-time-type").addEventListener("statistics-time",function (evt) {
        //时间回调
        queryUserTrendBoard(evt.detail.type,evt.detail.startTime,evt.detail.endTime);
    });

    //用户趋势看板
    initTimeType("user-time-type");
    //用户趋势看板的时间控件
    initTime("userStatTimeLaydate","userEndTimeLaydate",'user-time-type');
    //加载用户趋势看板
    queryUserTrendBoard(2,null,null);

    var nowDate = new Date();
    nowDate.setDate(nowDate.getDate() -1);
    var _max = (nowDate.getFullYear()+'-'+(nowDate.getMonth()+1)+"-"+nowDate.getDate());
    nowDate.setDate(nowDate.getDate()-365);
    var _min = (nowDate.getFullYear()+'-'+(nowDate.getMonth()+1)+"-"+nowDate.getDate());
    laydate({
        elem:"#payUserStatTimeLaydate",//需显示日期的元素选择器
        event: 'click', //触发事件
        format: 'YYYY-MM-DD', //日期格式
        istime: false, //是否开启时间选择
        istoday:false,
        value: new Date(),
        max:_max,
        min:_min,
        choose:function (dates) {
            queryPayUserCountData();
        }
    });
    var _nowDate = new Date();
    var month = _nowDate.getMonth()+1;
    if(month < 10){
        month = '0'+month;
    }
    var day = _nowDate.getDate();
    if(day < 10){
        day ='0'+day;
    }
    $("#payUserStatTimeLaydate").val(_nowDate.getFullYear()+'-'+month+"-"+day);
    //付款用户概况
    queryPayUserCountData();

    //用户注册渠道概况
    queryUserRegFormCountData();

    /**
     * 用户趋势看板数据
     * @param type
     * @param startTime
     * @param endTime
     */
    function queryUserTrendBoard(type,startTime,endTime) {
        $.ajax({
            url: baseloaction + '/admin/stat/queryUserTrendBoard',
            type:'post',
            dataType:'json',
            beforeSend:function(XH){
                $("#user-loading-box").removeClass("hide");
                return true;
            },
            data:{
                'type':type,
                'startTime':startTime,
                'endTime':endTime
            },
            success:function (result) {
                if(result.success==true){
                    var regUserCount = result.regUserCount;
                    showNum('regUserCount',regUserCount);

                    var activeUserCount = result.activeUserCount;
                    showNum('activeUserCount',activeUserCount);

                    var payUserCount = result.payUserCount;
                    showNum('payUserCount',payUserCount);

                    var userCount = result.userCount;
                    showNum('userCount',userCount);
                    //初始化用户趋势看板拆线图
                    initUserECharts(result);
                    $("#user-loading-box").addClass("hide");
                }
            }
        });
    }

    /**
     * 初始化用户趋势看板拆线图
     * @param result 返回结果
     */
    function initUserECharts(result) {
        //====================================
        //新增用户、总用户数 统计数据
        var userCountEntityList = result.userCountEntityList;
        //活跃用户数据列表
        var activeUserCountList = result.activeUserCountList;
        //付款用户统计列表
        var payUserCountList = result.payUserCountList;
        //X轴数据
        var xListData = result.xList;
        var xList = new Array();
        $.each(xListData,function (index,date) {
            if(result.type==1){//当天
                xList.push(date.split(":")[0]);
            }else{//历史数据
                xList.push(date.split(" ")[0]);
            }
        });
        var titleArr = new Array();
        if(result.type==1){//当天
            titleArr.push("新增用户");
            titleArr.push("付费用户");
            titleArr.push("总用户数");
        }else{//历史数据
            titleArr.push("新增用户");
            titleArr.push("活跃用户");
            titleArr.push("付费用户");
            titleArr.push("总用户数");
        }

        var series = new Array();
        var regUserNumList = new Array();
        $.each(userCountEntityList,function (index,userData) {
            regUserNumList.push(userData.regUserNum);
        });
        var color =[
            "#1890ff",
            "#2fc25b",
            "#fbd44b",
            "#f4667c",
            "#47D8BE"
        ];
        var regUserObj = {
            name:'新增用户',
            type:'line',
            data:regUserNumList,color: color[0],
            lineStyle: {
                normal: {
                    width: 3,
                    color: {
                        type: 'linear',

                        colorStops: [{
                            offset: 1,
                            color: color[0] // 0% 处的颜色
                        }],
                        globalCoord: false // 缺省为 false
                    }
                }
            },
            itemStyle: {
                normal: {
                    color: color[0],
                    borderWidth: 7,
                    borderColor:color[0]
                }
            },
            smooth: true
        };
        series.push(regUserObj);

        if(result.type !=1){
            var activeUserList = new Array();
            $.each(activeUserCountList,function (index,userData) {
                activeUserList.push(userData.userCount);
            });
            var activeUserObj = {
                name:'活跃用户',
                type:'line',
                data:activeUserList,color: color[1],
                lineStyle: {
                    normal: {
                        width: 3,
                        color: {
                            type: 'linear',

                            colorStops: [{
                                offset: 1,
                                color: color[1] // 0% 处的颜色
                            }],
                            globalCoord: false // 缺省为 false
                        }
                    }
                },
                itemStyle: {
                    normal: {
                        color: color[1],
                        borderWidth: 7,
                        borderColor:color[1]
                    }
                },
                smooth: true
            };
            series.push(activeUserObj);
        }else{
            var activeUserObj = {
                name:'',
                type:'line',
                data:[]
            };
            series.push(activeUserObj);
        }
        var payUserList = new Array();
        $.each(payUserCountList,function (index,userData) {
            payUserList.push(userData.payUserCount);
        });
        var payUserObj = {
            name:'付费用户',
            type:'line',
            data:payUserList,
            color: color[2],
            lineStyle: {
                normal: {
                    width: 3,
                    color: {
                        type: 'linear',

                        colorStops: [{
                            offset: 1,
                            color: color[2] // 0% 处的颜色
                        }],
                        globalCoord: false // 缺省为 false
                    }
                }
            },
            itemStyle: {
                normal: {
                    color: color[2],
                    borderWidth: 7,
                    borderColor:color[2]
                }
            },
            smooth: true
        };
        series.push(payUserObj);

        var userNumList = new Array();
        $.each(userCountEntityList,function (index,userData) {
            userNumList.push(userData.userNum);
        });
        var userNumObj = {
            name:'总用户数',
            type:'line',
            data:userNumList,
            color: color[3],
            lineStyle: {
                normal: {
                    width: 3,
                    color: {
                        type: 'linear',

                        colorStops: [{
                            offset: 1,
                            color: color[3] // 0% 处的颜色
                        }],
                        globalCoord: false // 缺省为 false
                    }
                }
            },
            itemStyle: {
                normal: {
                    color: color[3],
                    borderWidth: 7,
                    borderColor:color[3]
                }
            },
            smooth: true
        };
        series.push(userNumObj);
        var userBoardEChart = echarts.init(document.getElementById("user-trend-board"));
        var option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                color: color,
                data: titleArr,
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: xList
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: xList
            },
            yAxis: {
                type: 'value',
                splitLine: {
                    lineStyle: {
                        type: 'dashed',
                        color: '#DDD'
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: "#333"
                    },
                    onZero: false,
                },
                axisTick: {
                    alignWithLabel: true
                },
                nameTextStyle: {
                    color: "#999"
                },
                splitArea: {
                    show: false
                }
            },
            series:series
        };
        userBoardEChart.setOption(option);
        $(window).resize(userBoardEChart.resize);
    }

    /**
     * 查询付款用户概况数据
     * @param date
     */
    function queryPayUserCountData() {
        var date = $("#payUserStatTimeLaydate").val();
        $.ajax({
            url: baseloaction + '/admin/stat/queryPayUserCountData',
            type:'post',
            dataType:'json',
            data:{
                'date':date
            },
            success:function (result) {
                var obj = result.entity;
                if(parseInt(obj.payUserNum) > 0){
                    $("#userShare").text("100%");
                }else{
                    $("#userShare").text("--");
                }
                //客户数
                showUserPayText('payUserNum',obj.payUserNum,'');
                showUserPayText('newPayUserNum',obj.newPayUserNum,'');
                showUserPayText('oldPayUserNum',obj.oldPayUserNum,'');

                //客户数占比
                showUserPayText('newUserShare',obj.newUserShare,'%');
                showUserPayText('oldUserShare',obj.oldUserShare,'%');

                //平均客单价
                showUserPayText('averagePrice',obj.averagePrice,'');
                showUserPayText('newAveragePrice',obj.newAveragePrice,'');
                showUserPayText('oldAveragePrice',obj.oldAveragePrice,'');

                //付款金额
                showUserPayText('payPrice',obj.payPrice,'');
                showUserPayText('newPayPrice',obj.newPayPrice,'');
                showUserPayText('oldPayPrice',obj.oldPayPrice,'');

                //付款转化率
                showUserPayText('conversionRate',obj.conversionRate,'%');
                showUserPayText('newConversionRate',obj.newConversionRate,'%');
                showUserPayText('oldConversionRate',obj.oldConversionRate,'%');
            }
        });
    }


    /**
     * 用户注册渠道概况
     */
    function queryUserRegFormCountData() {
        setTimeout(function () {
            $.ajax({
                url: baseloaction + '/admin/stat/queryUserRegFormCountData',
                type:'post',
                dataType:'json',
                success:function (result) {
                    if(result.success==true){
                        var showTitle = [
                            "后台",
                            "IOS",
                            "安卓",
                            "小程序",
                            "IOS-QQ",
                            "安卓QQ",
                            "IOS-微信",
                            "安卓微信",
                            "IOS内购",
                            "H5",
                            "H5-QQ",
                            "H5-微信",
                            "PC-QQ",
                            "PC-微信",
                            "PC",
                            "学员卡"
                        ];
                        var obj = result.entity;
                        var showData = [
                            obj.adminFromNum,
                            obj.iosFromNum,
                            obj.androidFromNum,
                            obj.appletThirdWeiXinNum,
                            obj.iosThirdQQNum,
                            obj.androidThirdQQNum,
                            obj.iosThirdWeiXinNum,
                            obj.androidThirdWeiXinNum,
                            obj.iosNum,
                            obj.mobileFromNum,
                            obj.mobileThirdQQNum,
                            obj.mobileThirdWeiXinNum,
                            obj.pcThirdQQNum,
                            obj.pcThirdWeiXinNum,
                            obj.registerFromNum,
                            obj.userCardFromNum
                        ];
                        var regUserEChart = echarts.init(document.getElementById("user-reg-form-box"));
                        var option = {
                            color: ['#3398DB'],
                            tooltip : {
                                trigger: 'axis',
                                axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                                    type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                                }
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true
                            },
                            xAxis : [
                                {
                                    type : 'category',
                                    data :showTitle,
                                    axisTick: {
                                        alignWithLabel: true
                                    }
                                }
                            ],
                            yAxis : [
                                {
                                    type: 'value',
                                    splitLine: {
                                        lineStyle: {
                                            type: 'dashed',
                                            color: '#DDD'
                                        }
                                    },
                                    axisLine: {
                                        lineStyle: {
                                            color: "#333"
                                        },
                                        onZero: false
                                    },
                                    axisTick: {
                                        alignWithLabel: true
                                    },
                                    nameTextStyle: {
                                        color: "#999"
                                    },
                                    splitArea: {
                                        show: false
                                    }
                                }
                            ],
                            series : [
                                {
                                    name:'注册量',
                                    type:'bar',
                                    barWidth: '20%',
                                    data:showData
                                }
                            ]
                        };
                        regUserEChart.setOption(option);
                        $(window).resize(regUserEChart.resize);
                        $("#user-reg-form-box").css("background-color",'#fff');
                    }
                }
            });
        },500);
    }

    function showNum(id,num) {
        if(num > 9999){
            num = parseFloat(num / 10000).toFixed(2);
            $("#"+id).next().removeClass('hide');
        }else{
            if(num <=0){
                num = '--';
            }
        }
        $("#"+id).text(num);
    }

    function showUserPayText(id,num,suffix) {
        if(parseFloat(num) > 0){
            $("#"+id).text(num+suffix);
        }else{
            $("#"+id).text("--");
        }
    }
});